package controller;

import dao.UserDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.security.Principal;

@Controller
public class ProfileController {
    @Autowired
    private UserDAO userDao;

    @RequestMapping(value = "/profile", method = RequestMethod.GET)
    public String profile(ModelMap model, Principal principal) {
        model.addAttribute("username", userDao.getUser(principal.getName()).getUsername());
        model.addAttribute("role", userDao.getUser(principal.getName()).getRole());
        return "/profile";
    }

    @RequestMapping(value = "/profile", method = RequestMethod.POST)
    public String changePass(ModelMap model, Principal principal, @RequestParam("current") String current, @RequestParam("new") String pass, @RequestParam("confirm") String confirm) {
        if (current.contentEquals(userDao.getUser(principal.getName()).getPassword()))
             userDao.updatePass(principal.getName(), pass);
        model.addAttribute("username", userDao.getUser(principal.getName()).getUsername());
        return "/profile";
    }

    @RequestMapping(value = "/delete_profile", method = RequestMethod.GET)
    public String DeleteAccount(ModelMap model, Principal principal) {
        return "/delete_profile";
    }

    @RequestMapping(value = "/delete_profile", method = RequestMethod.POST)
    public String reallyDeleteAccount(Principal principal) {
        userDao.delete(principal.getName());
        return "/signin";
    }
}
